<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Springboot Generator 创建项目</title>
    <link rel="stylesheet" href="css/index.css" />
	<link rel="stylesheet" type="text/css" href="js/multiSelect/css/multiSelect.css">
	<style>
		.mt_select_container{
			width: 74% !important;
		}
	</style>
</head>
<body>
	<div class="container">
		<h1 class="header-title">Springboot Generator 创建项目</h1>
		<form id="projectForm" class="form" name="projectForm"
		      action="" method="post">
		    <div class="form-item">
				<div class="form-title">项目信息</div>
				<div class="form-content">
				    <div class="form-line">
				        <label>类型</label>
				        <div class="choose-line">
				            <label style="width: auto;">
				                <input type="radio" value="full" validate="required:true" name="projType"/> 完整项目
				            </label>
				            <label style="width: auto;margin-left: 20px;">
				                <input type="radio" value="single" validate="required:true" name="projType"/> 单表
				            </label>
				        </div>
				    </div>
				    <div class="form-line">
				        <label>项目名称</label>
				        <input type="text" name="projectName" validate="required:true" id="projectName" value="">
				    </div>
					<div class="form-line">
					    <label>项目简写</label>
					    <input type="text" name="projectSimpleName" validate="required:true" id="projectSimpleName" value="">
					</div>
				    <div class="form-line">
				        <label>项目包名</label>
				        <input type="text" name="packageName" validate="required:true" id="packageName" value="">
				    </div>
					<div class="form-line">
					    <label>系统名称</label>
					    <input type="text" name="projectSysName" validate="required:true" id="projectSysName" value="">
					</div>
					<div class="form-line">
					    <label>模块名称</label>
					    <input type="text" name="moduleName" validate="required:true" id="moduleName" value="">
					</div>
					<div class="form-line">
					    <label>前端页面</label>
					    <div class="choose-line">
					        <label style="width: auto;">
					            <input type="radio" value="Y" validate="required:true" name="createHtmlPage"/> 是
					        </label>
					        <label style="width: auto;margin-left: 20px;">
					            <input type="radio" value="N" validate="required:true" name="createHtmlPage"/> 否
					        </label>
					    </div>
					</div>
					<div class="form-line">
					    <label>基础访问路径</label>
					    <input type="text" name="accessBaseUrl" validate="required:true" id="accessBaseUrl" value="">
					</div>
				    <div class="form-line">
				        <label>端口</label>
				        <input type="number" name="port" validate="required:true" id="port" value="">
				    </div>
				    <div class="form-line">
				        <label>开发者名称</label>
				        <input type="text" name="author" validate="required:true" id="author" value="">
				    </div>
				</div>
			</div>
			<div class="form-item">
				<div class="form-title">数据库连接信息</div>
				<div class="form-content">
					<div class="form-line">
						<label>数据库类型</label>
						<select id="dbType" name="dbType" validate="required:true" onchange="changeDB(this.value)">
							
						</select>
					</div>
					<div class="form-line">
						<label>数据库驱动</label>
						<input type="text" name="driver" validate="required:true" id="driver">
					</div>
					<div class="form-line">
						<label>连接地址</label>
						<input type="text" name="url" id="url" validate="required:true">
					</div>
					<div class="form-line">
						<label>用户名</label>
						<input type="text" name="user" id="user" validate="required:true">
					</div>
					<div class="form-line">
						<label>密码</label>
						<input type="text" name="password" validate="required:true" id="password">
					</div>
					<div class="form-line" id="db2Schema" style="display: none;">
						<label>数据库模式</label>
						<input type="text" name="schema" validate="required:true" id="schema">
					</div>
					<div class="form-line singleTable" id="tablename-line" 
						style="display: none;line-height:normal;height: auto;">
						<label>表名</label>
						<select id="tableName" name="tableName" class="multi_select">
							
						</select>
					</div>
				</div>
			</div>
		    <div class="form-btn">
		        <input type="button" id="submit" class="btn" value="创建项目">
		        <input type="button" id="singleSubmit" style="margin-left: 20px;display: none;"
		               class="btn" value="创建单表类">
		    </div>
		</form>
	</div>
    <script type="application/javascript" src="js/jquery-2.0.3.min.js"></script>
    <script type="application/javascript" src="js/jquery.validate.js"></script>
	<script type="application/javascript" src="js/multiSelect/multiSelect.js"></script>
	<script type="application/javascript" src="js/server.js"></script>
    <script>
		
		var params = {
			projType: "full",
			projectName: "help-sys",
			projectSimpleName: "help",
			packageName: "cn.lanyumi",
			projectSysName: "一键呼救管理系统",
			moduleName: "user",
			createHtmlPage: "N",
			accessBaseUrl: "/v1/op/",
			port: "8080",
			author: "lanping"
		};
		
        var dbData = {
            dbType: [
                {
                    label: "MySQL",
                    code: "mysql"
                },
                {
                    label: "SQL Server",
                    code: "sqlserver"
                },
                {
                    label: "DB2",
                    code: "db2"
                }
            ],
            dbConn: [
                {
                    dbType: "mysql",
                    connector: {
                        driver: "com.mysql.cj.jdbc.Driver",
                        url: "jdbc:mysql://39.108.159.155:3306/medical_bill?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=UTC&allowPublicKeyRetrieval=true",
                        user: "root",
                        password: "2022Medicalbill&"
                    }
                },
                {
                    dbType: "sqlserver",
                    connector: {
                        driver: "com.microsoft.sqlserver.jdbc.SQLServerDriver",
                        url: "jdbc:sqlserver://127.0.0.1:1433;databaseName=base_db",
                        user: "sa",
                        password: "123456"
                    }
                },
                {
                    dbType: "db2",
                    connector: {
                        driver: "com.ibm.db2.jcc.DB2Driver",
                        url: "jdbc:db2://127.0.0.1:50000/base_db",
                        user: "db2admin",
                        password: "123456",
                        schema: "db2admin"
                    }
                }
            ]
        };
		
        var valid;
        $(function () {
            

            $("input[name='projType']").click(function () {
                if (this.value == "single") {
                    $(".singleTable").show();
                    $("#singleSubmit").show();
                    $("#submit").hide();
                } else if (this.value == "full") {
                    $(".singleTable").hide();
                    $("#singleSubmit").hide();
                    $("#submit").show();
                }
            });

            valid = $("#projectForm").validate({
                rules: {
                    projectName: {
                        required: true
                    }
                },
                messages: {
                    projectName: {
                        required: "请输入项目名称！"
                    }
                },
                submitHandler: function (form) {
                    form.submit();
                },
                invalidHandler: function (form, validator) {
                    return false;
                },
                errorElement: 'div',
                errorPlacement: function (error, element) {
                    error.addClass('tooltip tooltip-inner');
                    element.after(error);
                    var pos = $.extend({}, element.offset(), {
                            width: element.outerWidth()
                            , height: element.outerHeight()
                        }),
                        actualWidth = error.outerWidth(),
                        actualHeight = error.outerHeight();
                    error.css({
                        display: 'block',
                        opacity: '0.8',
                        top: pos.top - actualHeight,
                        left: pos.left + pos.width / 2 - actualWidth / 2
                    });
                },
                highlight: function (element, errorClass) {
                    //高亮显示
                    $(element).addClass(errorClass);
                    $(element).parents('li:first').children('label').addClass(errorClass);
                },
                unhighlight: function (element, errorClass) {
                    $(element).removeClass(errorClass);
                    $(element).parents('li:first').children('label').removeClass(errorClass);
                }
            })
        });

        function changeDB(val) {
            for (var i = 0; i < dbData.dbConn.length; i++) {
                if (val == dbData.dbConn[i].dbType) {
                    var conn = dbData.dbConn[i].connector;
                    $("#driver").val(conn.driver);
                    $("#url").val(conn.url);
                    $("#user").val(conn.user);
                    $("#password").val(conn.password);
                    $("#schema").val(conn.schema);
                    if (val == "db2") {
                        $("#db2Schema").show();
                    } else {
                        $("#db2Schema").hide();
                    }
                }
            }
        }

        $("#submit").click(function () {
            if (!valid.form()) {
                return;
            }
			var data = serializeObject($("#projectForm"));
            $.ajax({
                url: serverUrl + "/v1/createProject",
                type: "post",
                data: JSON.stringify(data),
				contentType: 'application/json',
				cache: false,
				async:true,
                success: function (res) {
                    if(res.code == 200){
						saveStorage(data);
                        var projectName = $("#projectName").val();
                        location.href = serverUrl+"/v1/download/" +
                            encodeURIComponent(encodeURIComponent(projectName)) + ".zip";
                    }
                }
            });
        });
		
		$("#user").on("blur",function(){
			var val = $("input[name='projType']:checked").val();
			if(val=='single'){
				$("input[name='projType'][value='single']").click();
			}
		});
		$("#password").on("blur",function(){
			var val = $("input[name='projType']:checked").val();
			if(val=='single'){
				$("input[name='projType'][value='single']").click();
			}
		});
		$("#driver").on("blur",function(){
			var val = $("input[name='projType']:checked").val();
			if(val=='single'){
				$("input[name='projType'][value='single']").click();
			}
		});
		$("#url").on("blur",function(){
			var val = $("input[name='projType']:checked").val();
			if(val=='single'){
				$("input[name='projType'][value='single']").click();
			}
		});
		
		$("#db2Schema").on("blur",function(){
			var val = $("input[name='projType']:checked").val();
			if(val=='single'){
				$("input[name='projType'][value='single']").click();
			}
		});
		
		$("#dbType").on("change",function(){
			var val = $("input[name='projType']").val();
			if(val=='single'){
				$("input[name='projType'][value='single']").click();
			}
		});
		
		

        $("#singleSubmit").click(function () {
			if (!valid.form()) {
			    return;
			}
			var data = serializeObject($("#projectForm"));
			var valArray=$("#tableName").multiVal();
			if(!valArray || valArray.length==0){
				alert("请选择表");
				return;
			}
			data.tableNames = valArray
			$.ajax({
			    url: serverUrl + "/v1/createCoderByTables",
			    type: "post",
			    data: JSON.stringify(data),
				contentType: 'application/json',
				cache: false,
				async:true,
			    success: function (res) {
			        if(res.code == 200){
						saveStorage(data);
			            var projectName = $("#projectName").val();
			            location.href = serverUrl+"/v1/download/" +
			                encodeURIComponent(encodeURIComponent(projectName)) + ".zip";
			        }
			    }
			});
        });
		
		$("input[name='projType']").click(function(){
			if (!valid.form()) {
			    return;
			}
			var data = serializeObject($("#projectForm"));
			$.ajax({
			    url: serverUrl + "/v1/tables",
			    type: "post",
			    data: JSON.stringify(data),
				contentType: 'application/json',
				cache: false,
				async:true,
			    success: function (res) {
			        if(res.code == 200){
						var selectData = [];
						if(res.data && res.data.length>0){
							$.each(res.data,function(index,item){
								var obj = {
									name:item.tableComment+"("+item.tableName+")",
									value:item.tableName
								};
								selectData.push(obj);
							})
						}
						showMultiSelect(selectData);
			        }
			    }
			});
		});
		
		showMultiSelect();
		
		function showMultiSelect(data){
			$("#tableName").multiSelect({
				label: '选择表',  // 可省略
				placeholder:'请选择表', // 可省略
				style:{  // 可省略
					width:'75%',
					height:'36px',
					lineHeight:'36px'
				},data:data
			});
		}
		
		function saveStorage(data){
			var json = JSON.stringify(data);
			localStorage.setItem("generator_cache",json);
		}
		
		function init(){
			var generator_cache = localStorage.getItem("generator_cache");
			if(generator_cache){
				var data = JSON.parse(generator_cache);
				showProject(data);
				var dbType = data.dbType
				for (var i = 0; i < dbData.dbConn.length; i++) {
				    if (dbType == dbData.dbConn[i].dbType) {
				        $("#driver").val(data.driver);
				        $("#url").val(data.url);
				        $("#user").val(data.user);
				        $("#password").val(data.password);
				        $("#schema").val(data.schema);
				        if (dbType == "db2") {
				            $("#db2Schema").show();
				        } else {
				            $("#db2Schema").hide();
				        }
				    }
				}
				showDatabase(dbType);
			}else{
				showProject(params);
				showDatabase("mysql");
			}
		}
		
		function showProject(data){
			$("input[name='projType'][value='full']").prop("checked",true);
			$("#projectName").val(data.projectName);
			$("#projectSimpleName").val(data.projectSimpleName);
			$("#packageName").val(data.packageName);
			$("#projectSysName").val(data.projectSysName);
			$("#moduleName").val(data.moduleName);
			$("input[name='createHtmlPage'][value='"+data.createHtmlPage+"']").prop("checked",true);
			$("#accessBaseUrl").val(data.accessBaseUrl);
			$("#port").val(data.port);
			$("#author").val(data.author);
		}
		
		function showDatabase(dbType){
			var dbTypes = '';
			for (var i = 0; i < dbData.dbType.length; i++) {
			    var select = '';
			    if (dbData.dbType[i].code == dbType) {
			        select = ' selected="selected"';
			    }
			    dbTypes += '<option value="' + dbData.dbType[i].code + '"' + select + '>' + dbData.dbType[i].label + '</option>';
			}
			$("#dbType").html(dbTypes);
			changeDB(dbType);
		}
		
		init();
    </script>
</body>
</html>